package gw.com.android.presenter.http;

import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.utils.CacheUtils;
import okhttp3.Request;
import okhttp3.Response;
import www.com.library.app.Logger;

/**
 * @author jett
 * @since 2017-11-23.
 */
public class TopNewsRequest {

    private static final int PAGE_SIZE = 20;

    private String cacheFileName = "_top_new2.dat";
    private int currPage;
    private int totalSize = -1;
    private boolean hasNextPage = false;

    public List<TopNewsData> fetchLocal() {
        String str = CacheUtils.readFile(cacheFileName);
        return parse(str, false);
    }

    public void call(HttpCallback<List<TopNewsData>> callBack) {
        currPage = 1;
        sendRequest(callBack);
    }

    private void sendRequest(final HttpCallback<List<TopNewsData>> callBack) {
        String url = ConfigUtil.instance().getUrlPath("openApi");
        new Https(url)
                .addParam("service", "Advisory.getList")
                .addParam("page", String.valueOf(currPage))
                .addParam("pageSize", String.valueOf(PAGE_SIZE))
                .addParam("utmTerminal", "app")//UMS接口，utmTerminal：终端类别
                .addParam("companyId", ConfigUtil.instance().mConfigObject.optString(ConfigType.COMPANY_ID_TAG))//公司ID：FT 18
                .addParam("url", "TOP_NEWS")//资讯栏目类别 可调节的标识
                .addParam("order", "toprtime")// 排序依据:toprtime表示 置顶+发布时间
                .get(new Https.ResponseCallback<String>() {
                    @Override
                    public void onSuccess(Request request, Response response, String result, int code) {
                        List<TopNewsData> list = parse(result, true);
                        if (callBack != null) {
                            callBack.onSuccess(list);
                        }
                    }

                    @Override
                    public void onFailure(Request request, IOException e) {
                        if (callBack != null) {
                            callBack.onFailure(e);
                        }
                    }
                });
    }

    public void nextPage(HttpCallback<List<TopNewsData>> callBack) {
        currPage++;
        sendRequest(callBack);
    }

    public boolean hasNextPage() {
        if (totalSize > 0) {
            return (totalSize - 1) / PAGE_SIZE > currPage - 1;
        }
        return hasNextPage;
    }

    private List<TopNewsData> parse(String str, boolean cache) {
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        try {
            JSONObject jsonObject = new JSONObject(str);
            JSONObject dataJson = jsonObject.optJSONObject("data");
            if (dataJson == null) {
                return null;
            }
            if (cache) {
                totalSize = dataJson.optInt("count");
            }
            JSONArray listArr = dataJson.optJSONArray("list");
            if (listArr == null || listArr.length() <= 0) {
                return null;
            }
            long serverTime = dataJson.optLong("serverTime");
            List<TopNewsData> list = new ArrayList<>();
            for (int i = 0; i < listArr.length(); i++) {
                JSONObject json = listArr.optJSONObject(i);
                if (json == null) {
                    continue;
                }
                TopNewsData news = new TopNewsData();
                news.id = json.optString("id");
                news.title = json.optString("title");
                news.serverTime = serverTime;
                news.releaseTime = json.optString("release_time");
                news.coverImg = json.optString("cover_img");
                news.isTop = "Y".equals(json.optString("is_top"));
                news.pviews = json.optInt("pviews");
                news.pviewsBase = json.optInt("pviews_base");
                news.remark = json.optString("remark");
                list.add(news);
            }
            hasNextPage = list.size() >= PAGE_SIZE;
            if (cache && currPage == 1) {
                CacheUtils.writeFile(cacheFileName, str);
            }
            return list;
        } catch (JSONException e) {
            Logger.e(e);
        }
        return null;
    }

    public void addPreview(String id) {
        String url = ConfigUtil.instance().getUrlPath("openApi");
        new Https(url).addParam("service", "Advisory.pviews").addParam("companyId", ConfigUtil.instance().mConfigObject.optString(ConfigType.COMPANY_ID_TAG)).addParam("id", id)
                .get(new Https.ResponseCallback<String>() {
                    @Override
                    public void onSuccess(Request request, Response response, String result, int code) {
                        Logger.i("TopNewsRequest", "add preview success : result = " + result);
                    }

                    @Override
                    public void onFailure(Request request, IOException e) {
                        Logger.e("TopNewsRequest", e);
                    }
                });
    }

    public class TopNewsData {
        public String id;
        public String title;
        public long serverTime;//服务器时间
        public String releaseTime;//发布时间
        public boolean isTop;//是否置顶
        public int pviews;//阅读量
        public int pviewsBase;// 基础阅读量
        public String coverImg;//封面
        public String remark;//摘要
    }

}
